import { appContext } from "@/models/app.context";
import router from "@/router";
import { hope } from "@/tools/hope/@types/hope";
import axios, { AxiosResponse } from "axios";
import { MessagePlugin } from "tdesign-vue-next";
import { getServiceErr } from "./msgerr";
import { NetStatusCode, config, StatusResp, RespResultCode } from "./request.services";



export interface ErrorInfo {
  status: NetStatusCode;
  errMsg: string;
  code: number;
}

export type BaseRespInfo = {
  code: RespResultCode;
  data: any;
  message: string;
}

export class BaseServices {
  constructor() { }

  private getHeader(): any {
    const token = appContext.global.token;
    return {
      "Access-Control-Allow-Origin": "*",
      "Content-Type": "application/json; charset=utf-8",
      token
    }
  }
  /**
   * 网络请求统一处理
   * @param url 地址
   * @param data 参数
   * @param isLocal 是否开启本地调试
   * @returns 
   */
  public request<T>(uri: string, data: Object, isLocal?: boolean, method: "POST" | "OPTIONS" | "GET" | "HEAD" | "PUT" | "DELETE" | "TRACE" | "CONNECT" = "POST", headers?: any): Promise<T> {
    headers = headers || this.getHeader();
    const url = (isLocal ? '' : config.httpHost) + uri;
    return new Promise<T>((resolve, reject) => {
      axios({ url, method, data, headers }).then((res: any) => {
        console.log("%c url：" + url, 'background:#41b883;color:#fff;border-radius: 0px;border: 2px solid #41b883;padding: 0 2px');
        console.log('Request:', data);
        console.log('Response:', res);
        if (this.checkResp(res)) {
          resolve(res.data.data as T);
        } else {
          reject()
        }
      }).catch(err => {
        console.error('request error', err);
        const { message } = err.response.data;
        MessagePlugin('error', message)
        reject(err);
      })
    });
  }
  public get<T>(url: string): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      axios.get(url).then((res: any) => {
        if (this.checkResp(res.data?.status)) {
          resolve(res.data as T);
        }
      }).catch(err => {
        reject(err);
      })
    });
  }

  private checkResp(res: AxiosResponse<BaseRespInfo>): boolean {
    if (res.status === 200) {
      const { code, message } = res.data;
      // if (data.token) AppContext.instance.setGlobal({ token: data.token });  // 更新token
      if (code !== RespResultCode.Success) {
        MessagePlugin("error", message);
        if ([RespResultCode.TokenEmpty, RespResultCode.TokenExpire, RespResultCode.TokenMiss].includes(code)) {
          localStorage.removeItem('token')
          router.replace("/login");
        }
        return false;
      }
      return true;
    }
    return false;
  }
}
